﻿using AzureFileDepot.HelperClasses;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using AzureFileDepot.Helpers;

namespace PublishingService
{
    public partial class PublishingService : ServiceBase
    {
        FileWatcher watcher;
        static ServiceBusTopic topic;

        public PublishingService()
        {
            InitializeComponent();
            this.ServiceName = "AzureFileDepot Publisher";
            this.EventLog.Source = "AzureFileDepot";
            this.EventLog.Log = "Application";

            if (!EventLog.SourceExists(this.EventLog.Source))
                EventLog.CreateEventSource(this.EventLog.Source, "Application");

            topic = new ServiceBusTopic(Properties.Settings.Default.ServiceBusTopic, "filepublication");

            watcher = new FileWatcher(Properties.Settings.Default.FileWatchLocation, "*.*");
        }

        protected override void OnStart(string[] args)
        {
            this.EventLog.WriteEntry(string.Format("Starting Service '{0}'", this.ServiceName));

            watcher.Start(FileFound);

            base.OnStart(args);
        }

        protected override void OnStop()
        {
            this.EventLog.WriteEntry(string.Format("Stopping Service '{0}'", this.ServiceName));

            watcher.Stop();
        }

        public static void FileFound(FileInfo foundFileInfo, Stream foundFileStream)
        {
            // use blockblob and service bus helpers to upload file and broadcast
            AzureBlob newBlob = new AzureBlob(Properties.Settings.Default.AzureStorageConnection, Properties.Settings.Default.UploadContainer);
            newBlob.uploadFromStream(foundFileStream, foundFileInfo.Name);

            topic.SendMessage(newBlob.CreateReadSaS(Properties.Settings.Default.UploadContainer, foundFileInfo.Name));
        }

    }
}
